#include "sys_hardware.h"

uint32_t timer_now;
static void uart1_init(void);

void sys_nvic_init(void) {
    FL_NVIC_ConfigTypeDef    InterruptConfigStruct;
    InterruptConfigStruct.preemptPriority = 2;
    FL_NVIC_Init(&InterruptConfigStruct, UART1_IRQn);
}

void sys_hardware_init(void) {
    uart1_init();
    FL_DMA_Enable(DMA);
}

// 与ESP32通讯
static void uart1_init(void) {
    FL_GPIO_InitTypeDef GPIO_InitStruct;
    GPIO_InitStruct.pin = FL_GPIO_PIN_2 | FL_GPIO_PIN_3;
    GPIO_InitStruct.mode = FL_GPIO_MODE_DIGITAL;
    GPIO_InitStruct.outputType = FL_GPIO_OUTPUT_PUSHPULL;
    GPIO_InitStruct.pull = FL_DISABLE;
    GPIO_InitStruct.remapPin = FL_DISABLE;
    FL_GPIO_Init(GPIOC, &GPIO_InitStruct);

    FL_RCC_SetUART1ClockSource(FL_RCC_UART1_CLK_SOURCE_RCHF);
    FL_RCC_EnableGroup3BusClock(FL_RCC_GROUP3_BUSCLK_UART1);
    FL_RCC_EnableGroup1OperationClock(FL_RCC_GROUP1_OPCLK_UART1);
    FL_UART_WriteBaudRate(UART1, (FL_RCC_GetRCHFClockFreq() / 115200) - 1);
    FL_UART_SetStopBitsWidth(UART1, FL_UART_STOP_BIT_WIDTH_1B);
    FL_UART_SetDataWidth(UART1, FL_UART_DATA_WIDTH_8B);
    FL_UART_SetParity(UART1, FL_UART_PARITY_NONE);


    FL_DMA_InitTypeDef  dma_init;
    dma_init.periphAddress = FL_DMA_PERIPHERAL_FUNCTION3;
    dma_init.direction = FL_DMA_DIR_RAM_TO_PERIPHERAL;
    dma_init.memoryAddressIncMode = FL_DMA_MEMORY_INC_MODE_INCREASE;
    dma_init.flashAddressIncMode = FL_DMA_CH7_FLASH_INC_MODE_INCREASE;
    dma_init.dataSize = FL_DMA_BANDWIDTH_8B;
    dma_init.priority = FL_DMA_PRIORITY_HIGH;
    dma_init.circMode = FL_DISABLE;
    FL_DMA_Init(DMA, &dma_init, FL_DMA_CHANNEL_6);
}

void HardFault_Handler(void) {
    for (;;) {

    }
}

#ifdef  USE_FULL_ASSERT
void assert_failed(uint8_t *file, uint32_t line)
{
    /* USER CODE BEGIN Assert_Failed */
    /* User can add his own implementation to report the file name and line number,
       tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
    /* USER CODE END Assert_Failed */
}
#endif /* USE_FULL_ASSERT */
